//
//  CS_Pop_SelectView.m
//  Pods
//
//  Created by 网新中研 on 17/3/1.
//
//

#import "CS_Pop_SingleSelectView.h"

#define SELECT_VIEW_WIDTH (kWindowW)
#define SELECT_CELL_HEIGHT 60
#define SELECT_CELL_MARGIN 30.0
#define CONTENT_LABEL_HEIGHT 40.0

@implementation CSSelectTableViewCell

-(instancetype)init{
    if (self = [super init]) {
        [self.contentView addSubview:self.contentLabel];
    }
    return self;
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self.contentView addSubview:self.contentLabel];
//        CGRectMake(30,10.0, SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN, CONTENT_LABEL_HEIGHT);
        UIView *dashLineView = [UIView new];
        dashLineView.frame = CGRectMake(SELECT_CELL_MARGIN, SELECT_CELL_HEIGHT-1, SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN, 1);
//        dashLineView.backgroundColor = COLOR_TOP_SEPERATOR_LINE;
        
        [self drawLineOfDashByCAShapeLayer:dashLineView lineLength:10 lineSpacing:5 lineColor:COLOR_TOP_SEPERATOR_LINE lineDirection:YES];
        [self.contentView addSubview:dashLineView];
    }
    return self;
}

-(UIFont *)getAdjustFont{
    CGFloat deviationHeight = 0.0;
    UIFont *resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL];
    CGFloat needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
    if (needHeight > CONTENT_LABEL_HEIGHT - deviationHeight) {
        resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL - 2.0];
        needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
        if (needHeight > CONTENT_LABEL_HEIGHT - deviationHeight) {
            resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL - 4.0];
            needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
            if (needHeight > CONTENT_LABEL_HEIGHT - deviationHeight) {
                resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL - 6.0];
                needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
                if (needHeight > CONTENT_LABEL_HEIGHT - deviationHeight) {
                    resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL - 8.0];
                    needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
                    if (needHeight > CONTENT_LABEL_HEIGHT - deviationHeight) {
                        resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL - 10.0];
                        needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
                        if (needHeight > CONTENT_LABEL_HEIGHT - deviationHeight) {
                            resultFont = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL - 12.0];
                            needHeight = [self estimateHeight:self.contentLabel.text font:resultFont width:SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN];
                        }
                    }
                }
            }
        }
    }
    return resultFont;
}

- (UILabel *)contentLabel {
    if(_contentLabel == nil) {
        _contentLabel = [[UILabel alloc] init];
        _contentLabel.frame = CGRectMake(30,10.0, SELECT_VIEW_WIDTH - 2 * SELECT_CELL_MARGIN, CONTENT_LABEL_HEIGHT);
        _contentLabel.font = [UIFont systemFontOfSize:FONT_SIZE_POP_SELECT_CELL];
        _contentLabel.numberOfLines = 0;
        _contentLabel.textColor = COLOR_TEXT_1;
    }
    return _contentLabel;
}

@end

@interface CS_Pop_SingleSelectView()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray *selectItems;

@property (nonatomic, copy) CSSelectBlock selectHandler;

@property (nonatomic, copy) CSSelectBlock2 selectHandler2;

/**
 *  标题
 */
@property (nonatomic, strong) NSString *title;

/**
 *  表格
 */
@property (strong, nonatomic) UITableView *tableView;

/**
 *  标题标签
 */
@property (strong, nonatomic) UILabel *titleLabel;

/**
 *  头部视图
 */
@property (strong, nonatomic) UIView *headView;

/**
 * 是否出在查询模式下
 */
@property (nonatomic, assign) BOOL isQueryModel;

/**
 * 最终显示在列表上的模型对象
 */
@property (nonatomic, strong) NSMutableArray *finalDisplayModels;

/**
 * 是否为模型选项
 */
@property (nonatomic, assign) BOOL isModelSelectType;

/**
 * 是否分类处理
 */
@property (nonatomic, assign) BOOL isCategorySelectItems;

@end

@implementation CS_Pop_SingleSelectView

/************************************************方案1：用字符串数组的方式********************************************/
+(instancetype)pop_SingleSelectView:(NSString *)title selectItems:(NSArray *)selectItems selectHandler:(CSSelectBlock)selectHandler{
    
    CS_Pop_SingleSelectView *pop_SelectView = [[CS_Pop_SingleSelectView alloc]init];
    pop_SelectView.selectItems = selectItems;
    pop_SelectView.selectHandler = selectHandler;
    pop_SelectView.title = title;
    pop_SelectView.titleLabel.text = title;
    [pop_SelectView layoutView];
    
    
    NSInteger rowCount = selectItems.count< 7 ? selectItems.count: 7;
    pop_SelectView.frame = CGRectMake(0, 0, SELECT_VIEW_WIDTH, rowCount * SELECT_CELL_HEIGHT);
    
    return pop_SelectView;
}

/************************************************方案2：用传SelectModel数组的方式********************************************/
+(instancetype)pop_SingleSelectViewForModel:(NSString *)title selectItems:(NSArray *)selectItems selectHandler:(CSSelectBlock2)selectHandler{
    CS_Pop_SingleSelectView *pop_SelectView = [[CS_Pop_SingleSelectView alloc]init];
    pop_SelectView.selectItems = selectItems;
    pop_SelectView.selectHandler2 = selectHandler;
    pop_SelectView.title = title;
    pop_SelectView.titleLabel.text = title;
    pop_SelectView.isModelSelectType = YES;
    [pop_SelectView initFinalDisplayModels];//初始化要显示的列表项
    [pop_SelectView layoutView];
    
    NSInteger rowCount = selectItems.count< 7 ? selectItems.count: 7;
    pop_SelectView.frame = CGRectMake(0, 0, SELECT_VIEW_WIDTH, rowCount * SELECT_CELL_HEIGHT);
    
    return pop_SelectView;
}

/************************************************方案4：查询模式********************************************/
+(instancetype)query_SingleSelectViewForSelectItems:(NSArray *)selectItems selectHandler:(CSSelectBlock)selectHandler{
    
    CS_Pop_SingleSelectView *pop_SelectView = [[CS_Pop_SingleSelectView alloc]init];
    pop_SelectView.selectItems = selectItems;
    pop_SelectView.selectHandler = selectHandler;
    pop_SelectView.isQueryModel = YES;
    [pop_SelectView layoutView];
    
    
    NSInteger rowCount = selectItems.count < 6 ? selectItems.count : 6;
    pop_SelectView.frame = CGRectMake(0, 0, SELECT_VIEW_WIDTH, rowCount * SELECT_CELL_HEIGHT);
    
    return pop_SelectView;
    
}


-(void)layoutView{
    
//    if (self.isQueryModel) {
        //标题
//        self.titleLabel.text = self.title;
//        self.titleLabel.font = [UIFont systemFontOfSize:17.0];
//        self.titleLabel.textColor = COLOR_WHITE;
//        self.titleLabel.textAlignment = NSTextAlignmentCenter;
//        self.titleLabel.frame = CGRectMake(0, 0, SELECT_VIEW_WIDTH, SELECT_CELL_HEIGHT);
//        [self addSubview:self.titleLabel];
//    }
    
    //列表
    self.backgroundColor = COLOR_WHITE;
    [self addSubview:self.tableView];
    
}

/**
 * 初始化最终要显示在视图列表上的视图模型
 */
-(void)initFinalDisplayModels{
    
    self.isCategorySelectItems = NO;
    for (CSSelectableModel *selectableModel in self.selectItems) {
        [self.finalDisplayModels addObject:selectableModel];
        for (CSSelectableModel *model in selectableModel.subItems) {
            [self.finalDisplayModels addObject:model];
            self.isCategorySelectItems = YES;
        }
    }
}

/**
 * 判断是否为第一层选择项
 */
-(BOOL)isParentModel:(CSSelectableModel *)selectableModel{
    
    for (CSSelectableModel *model in self.selectItems) {
        if (selectableModel == model) {
            return YES;
        }
    }
    
    return NO;
}



#pragma mark --- UITableViewDelegate, UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.isModelSelectType) {
        return self.selectItems == nil ? 0 : self.finalDisplayModels.count;
    }
    
    return self.selectItems == nil ? 0 : self.selectItems.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.isModelSelectType) {
        
        if (!self.isCategorySelectItems) {
            
            CSSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
            
            CSSelectableModel *model = (CSSelectableModel *)[self.selectItems objectAtIndex:indexPath.row];
            if (cell == nil) {
                cell = [[CSSelectTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            }
            
            cell.contentLabel.text = model.content;
            cell.contentLabel.font = [cell getAdjustFont];
            
            return cell;
            
        }else{
            CSSelectableModel *model = [self.finalDisplayModels objectAtIndex:indexPath.row];
            
            if (![self isParentModel:model]) {
                SubSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_STYLE_SUB_SELECTALBE_CELL];
                if (cell==nil) {
                    cell = [[SubSelectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_STYLE_SUB_SELECTALBE_CELL];
                }
                cell.model = model;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
                
            }else{
                MainSelectCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_STYLE_MAIN_SELECTABLE_CELL];
                if (cell==nil) {
                    cell = [[MainSelectCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_STYLE_MAIN_SELECTABLE_CELL];
                }
                cell.model = model;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }
        
        
        
    } else {
        
        CSSelectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        
        NSString *selectableString = (NSString *)[self.selectItems objectAtIndex:indexPath.row];
        if (cell == nil) {
            cell = [CSSelectTableViewCell new];
        }
        
        cell.contentLabel.text = selectableString;
        cell.contentLabel.font = [cell getAdjustFont];
        
        return cell;
    }
    return nil;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return SELECT_CELL_HEIGHT;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *selectString = @"";
    CSSelectableModel *selectModel = [CSSelectableModel new];
    
    if (self.isModelSelectType) {
        selectModel = [self.finalDisplayModels objectAtIndex:indexPath.row];
        selectString = (selectModel.name == nil ? selectModel.content : selectModel.name);
        
        if (self.isCategorySelectItems && [self isParentModel:selectModel]) {
            return;
        }
        
    }else{
        NSObject *model = [self.selectItems objectAtIndex:indexPath.row];
        selectString = (NSString *)model;
    }
    
    if (self.selectHandler != nil) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        self.selectHandler(0, indexPath.row, selectString);
        [self.superKLCPopup dismiss:YES];
    }
    
    if (self.selectHandler2 != nil) {
        [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
        self.selectHandler2(0, indexPath.row, selectModel);
        [self.superKLCPopup dismiss:YES];
    }
    
}

//-(void)popShow{
//    //Show in popup
//    KLCPopupLayout layout = KLCPopupLayoutMake(KLCPopupHorizontalLayoutRight,
//                                               KLCPopupVerticalLayoutCenter);
//    
//    KLCPopup* popup = [KLCPopup popupWithContentView:self
//                                            showType:KLCPopupShowTypeSlideInFromRight
//                                         dismissType:KLCPopupDismissTypeSlideOutToRight
//                                            maskType:KLCPopupMaskTypeClear
//                            dismissOnBackgroundTouch:YES
//                               dismissOnContentTouch:NO];
//    self.superKLCPopup = popup;
////    self.layer.cornerRadius = 5;
//    self.layer.shadowOpacity = 0.3;
//    self.layer.shadowColor = [UIColor blackColor].CGColor;
//    self.layer.shadowOffset = CGSizeMake(0, 1);
//    
//    [popup showWithLayout:layout];
//}

-(UITableView *)tableView{
    
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]init];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = [UIColor clearColor];
        [_tableView registerClass:[MainSelectCell class] forCellReuseIdentifier:CELL_STYLE_MAIN_SELECTABLE_CELL];
        [_tableView registerClass:[SubSelectCell class] forCellReuseIdentifier:CELL_STYLE_SUB_SELECTALBE_CELL];
        [_tableView registerClass:[CSSelectTableViewCell class] forCellReuseIdentifier:@"cell"];
        _tableView.rowHeight = SELECT_CELL_HEIGHT;
        STYLE_TABLE_VIEW(_tableView);
        _tableView.frame = CGRectMake(0, 0, SELECT_VIEW_WIDTH, 7 * SELECT_CELL_HEIGHT);
        if (self.isQueryModel) {
            
            NSInteger rowCount = _selectItems.count < 6 ? _selectItems.count: 6;
            _tableView.frame = CGRectMake(0, 0, kWindowW, rowCount * SELECT_CELL_HEIGHT);
            
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
    
}

-(NSMutableArray *)finalDisplayModels{
    if (_finalDisplayModels == nil) {
        _finalDisplayModels = [NSMutableArray new];
    }
    return _finalDisplayModels;
}

@end
